package leetcode.L500;

import java.util.LinkedList;
import java.util.List;

public class EX54 {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new LinkedList<>();
        int left = 0;
        int up = 0;
        int right = matrix[0].length-1;
        int down = matrix.length-1;

        int i = 0;
        int j = 0;

        while (true) {
            for (; i < right; i++) {
                res.add(matrix[j][i]);
            }
            up++;
            if(up>=down){break;}
            for (; j < down; j++) {
                res.add(matrix[j][i]);
            }
            right--;
            if(left>=right){break;}
            for(; i >left; i--){
                res.add(matrix[j][i]);
            }
            down--;
            if(up>=down){break;}
            for (;j>up;j--){
                res.add(matrix[j][i]);
            }
            left++;
            if(left>=right){break;}
        }
        return res;

    }
}
